<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>越南时事新闻汉越双语平行语料库 - 编辑语料库</title>
    <link rel="stylesheet" href="css/common.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
        }

        /* 顶部导航栏 */
        .header {
            background: #c41e3a;
            color: white;
            padding: 0 20px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 18px;
            font-weight: bold;
        }

        .logo::before {
            content: "🏛️";
            margin-right: 8px;
            font-size: 20px;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-links a {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 4px;
            transition: background 0.3s ease;
        }

        .nav-links a:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        /* 主内容区域 */
        .main-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        /* 页面标题 */
        .page-header {
            text-align: center;
            margin-bottom: 40px;
        }

        .page-title {
            font-size: 32px;
            font-weight: bold;
            color: #c41e3a;
            margin-bottom: 10px;
        }

        .page-subtitle {
            font-size: 16px;
            color: #666;
        }

        /* 表单区域 */
        .form-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            padding: 40px;
            position: relative;
        }

        .form-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: #c41e3a;
            border-radius: 12px 12px 0 0;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-label.required::after {
            content: ' *';
            color: #c41e3a;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: #fafafa;
        }

        .form-input:focus {
            outline: none;
            border-color: #c41e3a;
            background: white;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        .form-input::placeholder {
            color: #999;
        }

        .form-textarea {
            min-height: 120px;
            resize: vertical;
        }

        .form-select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            background: #fafafa;
            transition: all 0.3s ease;
        }

        .form-select:focus {
            outline: none;
            border-color: #c41e3a;
            background: white;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        /* 语言循环按钮样式 */
        .language-toggle {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
            min-height: 48px;
        }

        .language-toggle:hover {
            border-color: #c41e3a;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        .language-toggle.focused {
            border-color: #c41e3a;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        .language-display {
            flex: 1;
            font-size: 16px;
            color: #333;
        }

        .language-arrow {
            font-size: 18px;
            color: #666;
            transition: transform 0.2s ease;
        }

        .language-toggle:hover .language-arrow {
            color: #c41e3a;
            transform: rotate(90deg);
        }

        /* 只读语言显示样式 */
        .language-display-readonly {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            background: #f8f9fa;
            font-size: 16px;
            color: #333;
            min-height: 48px;
        }

        .language-note {
            margin-top: 8px;
        }

        .language-note small {
            color: #666;
            font-style: italic;
        }

        /* 按钮区域 */
        .button-section {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-top: 40px;
        }

        .btn {
            padding: 14px 30px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 120px;
        }

        .btn-primary {
            background: #c41e3a;
            color: white;
        }

        .btn-primary:hover {
            background: #a0172e;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(196, 30, 58, 0.3);
        }

        .btn-secondary {
            background: #f5f5f5;
            color: #666;
            border: 2px solid #e0e0e0;
        }

        .btn-secondary:hover {
            background: #e0e0e0;
            transform: translateY(-1px);
        }

        .btn:disabled {
            background: #ccc;
            color: #999;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        /* 错误提示 */
        .error-message {
            background: #fee;
            color: #c41e3a;
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 14px;
            border-left: 4px solid #c41e3a;
            display: none;
        }

        /* 成功提示 */
        .success-message {
            background: #efe;
            color: #2d5a2d;
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 14px;
            border-left: 4px solid #2d5a2d;
            display: none;
        }

        /* 加载动画 */
        .loading {
            display: none;
            text-align: center;
            margin-top: 20px;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #c41e3a;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-container {
                padding: 20px;
            }

            .form-section {
                padding: 30px 20px;
            }

            .page-title {
                font-size: 24px;
            }

            .button-section {
                flex-direction: column;
            }

            .nav-links {
                display: none;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <header class="header">
        <div class="logo">
            <span>越南时事新闻汉越双语平行语料库</span>
        </div>
        
        <nav class="nav-links">
            <a href="index.html">首页</a>
            <a href="corpus-libraries.html">语料库</a>
        </nav>

        <div class="user-info">
            <div class="user-avatar">👤</div>
            <span id="userName">用户</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-container">
        <!-- 页面标题 -->
        <section class="page-header">
            <h1 class="page-title">编辑语料库</h1>
            <p class="page-subtitle">修改语料库信息</p>
        </section>

        <!-- 表单区域 -->
        <section class="form-section">
            <!-- 错误提示 -->
            <div class="error-message" id="errorMessage"></div>
            
            <!-- 成功提示 -->
            <div class="success-message" id="successMessage"></div>

            <form id="editForm">
                <div class="form-group">
                    <label class="form-label required" for="name">语料库名称</label>
                    <input 
                        type="text" 
                        id="name" 
                        name="name" 
                        class="form-input" 
                        placeholder="请输入语料库名称"
                        maxlength="100"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="description">语料库描述</label>
                    <textarea 
                        id="description" 
                        name="description" 
                        class="form-input form-textarea" 
                        placeholder="请输入语料库描述（可选）"
                        maxlength="500"
                    ></textarea>
                </div>

                <div class="form-group">
                    <label class="form-label required" for="domain">领域分类</label>
                    <select id="domain" name="domain" class="form-select" required>
                        <option value="">请选择领域分类</option>
                        <option value="政治">政治</option>
                        <option value="经济">经济</option>
                        <option value="文化">文化</option>
                        <option value="科技">科技</option>
                        <option value="体育">体育</option>
                        <option value="社会">社会</option>
                        <option value="其他">其他</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">语言配置</label>
                    <div class="language-display-readonly" id="languageDisplayReadonly">
                        中文 → 越南语
                    </div>
                    <div class="language-note">
                        <small>💡 语言配置创建后不可修改，以保证语料数据的一致性</small>
                    </div>
                    <input type="hidden" id="sourceLang" name="sourceLang" value="zh">
                    <input type="hidden" id="targetLang" name="targetLang" value="vi">
                </div>

                <div class="form-group">
                    <label class="form-label" for="status">状态</label>
                    <select id="status" name="status" class="form-select">
                        <option value="active">活跃</option>
                        <option value="inactive">非活跃</option>
                        <option value="archived">已归档</option>
                    </select>
                </div>
            </form>

            <!-- 按钮区域 -->
            <div class="button-section">
                <button type="button" class="btn btn-secondary" onclick="goBack()">
                    取消
                </button>
                <button type="submit" class="btn btn-primary" onclick="submitForm()">
                    保存修改
                </button>
            </div>

            <!-- 加载动画 -->
            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
                <span style="margin-left: 10px;">保存中...</span>
            </div>
        </section>
    </main>

    <script>
        let corpusLibraryId = null;
        
        // 语言映射
        const languageMap = {
            'zh': '中文',
            'vi': '越南语'
        };

        // 页面加载时检查登录状态和获取语料库信息
        window.addEventListener('load', function() {
            checkLoginStatus();
            getCorpusLibraryId();
            loadCorpusLibraryData();
        });

        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const user = localStorage.getItem('user');
            
            if (!token) {
                window.location.href = 'login.html';
                return;
            }
            
            if (user) {
                try {
                    const userData = JSON.parse(user);
                    document.getElementById('userName').textContent = userData.username || '用户';
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }
        }

        // 获取语料库ID
        function getCorpusLibraryId() {
            const urlParams = new URLSearchParams(window.location.search);
            corpusLibraryId = urlParams.get('id');
            
            if (!corpusLibraryId) {
                showError('缺少语料库ID参数');
                return;
            }
        }

        // 加载语料库数据
        async function loadCorpusLibraryData() {
            if (!corpusLibraryId) return;

            try {
                const response = await fetch(`/corpus/libraries/get/${corpusLibraryId}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 200) {
                        fillFormData(result.data);
                    } else {
                        showError('加载语料库信息失败：' + result.msg);
                    }
                } else {
                    showError('网络错误，请稍后重试');
                }
            } catch (error) {
                console.error('加载语料库数据错误:', error);
                showError('加载失败，请稍后重试');
            }
        }

        // 填充表单数据
        function fillFormData(data) {
            document.getElementById('name').value = data.name || '';
            document.getElementById('description').value = data.description || '';
            document.getElementById('domain').value = data.domain || '';
            // 设置语言配置（只读显示）
            const sourceLang = data.sourceLang || 'zh';
            const targetLang = data.targetLang || 'vi';
            
            const sourceLangName = languageMap[sourceLang] || sourceLang;
            const targetLangName = languageMap[targetLang] || targetLang;
            
            // 显示语言配置
            document.getElementById('languageDisplayReadonly').textContent = `${sourceLangName} → ${targetLangName}`;
            
            // 设置隐藏字段
            document.getElementById('sourceLang').value = sourceLang;
            document.getElementById('targetLang').value = targetLang;
            document.getElementById('status').value = data.status || 'active';
        }

        // 提交表单
        async function submitForm() {
            const form = document.getElementById('editForm');
            const formData = new FormData(form);
            
            const data = {
                name: formData.get('name').trim(),
                description: formData.get('description').trim(),
                domain: formData.get('domain'),
                sourceLang: formData.get('sourceLang'),
                targetLang: formData.get('targetLang'),
                status: formData.get('status')
            };

            // 基本验证
            if (!data.name) {
                showError('请输入语料库名称');
                return;
            }

            if (!data.domain) {
                showError('请选择领域分类');
                return;
            }

            // 语言配置在编辑时不可修改，无需验证

            const loading = document.getElementById('loading');
            const submitBtn = document.querySelector('.btn-primary');
            
            // 显示加载状态
            loading.style.display = 'block';
            submitBtn.disabled = true;
            submitBtn.textContent = '保存中...';

            try {
                const response = await fetch(`/corpus/libraries/update/${corpusLibraryId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (response.ok && result.code === 200) {
                    showSuccess('语料库修改成功！正在跳转...');
                    
                    // 延迟跳转到语料库列表页
                    setTimeout(() => {
                        window.location.href = 'corpus-libraries.html';
                    }, 1500);
                } else {
                    showError(result.msg || '修改失败，请检查输入信息');
                }
            } catch (error) {
                console.error('修改语料库错误:', error);
                showError('网络错误，请稍后重试');
            } finally {
                // 隐藏加载状态
                loading.style.display = 'none';
                submitBtn.disabled = false;
                submitBtn.textContent = '保存修改';
            }
        }

        // 返回上一页
        function goBack() {
            if (confirm('确定要取消修改吗？未保存的数据将丢失。')) {
                window.history.back();
            }
        }

        // 显示错误消息
        function showError(message) {
            const errorMessage = document.getElementById('errorMessage');
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            
            // 隐藏成功消息
            document.getElementById('successMessage').style.display = 'none';
        }

        // 显示成功消息
        function showSuccess(message) {
            const successMessage = document.getElementById('successMessage');
            successMessage.textContent = message;
            successMessage.style.display = 'block';
            
            // 隐藏错误消息
            document.getElementById('errorMessage').style.display = 'none';
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = 'login.html';
            }
        }

        // 表单验证
        document.getElementById('editForm').addEventListener('input', function() {
            // 清除错误消息
            document.getElementById('errorMessage').style.display = 'none';
        });

        // 回车键提交
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') {
                submitForm();
            }
        });
    </script>
</body>
</html>
